package com.github.prontera.model;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import com.github.prontera.domain.Tags;

/** 
 * 树形结构构建
 */  
public class TreeUtll{  
    
	/** 
     * 说明方法描述：将list转为树tree结构 
     */  
    public static List<Tags> treeTags(List<Tags> allRrecords) {  
        List<Tags> listParentTreeNode = new ArrayList<Tags>();  
        List<Tags> listNotParentTreeNode = new ArrayList<Tags>();  
        // 第一步：遍历allRrecords保存所有数据的uuid用于判断是不是根节点  
        Set<Long> mapAllUuid = new HashSet<Long>();  
        for (Tags record : allRrecords) {  
            mapAllUuid.add(record.getId());  
        }  
        // 第二步：遍历allRrecords找出所有的根节点和非根节点  
        if (allRrecords != null && allRrecords.size() > 0) {  
            for (Tags record : allRrecords) {  
                if (record.getParentId()==null  
                    || !mapAllUuid.contains(record.getParentId())) {  
                    listParentTreeNode.add(record);  
                } else {  
                    listNotParentTreeNode.add(record);  
                }  
            }  
        }  
        // 第三步： 递归获取所有子节点  
        if (listParentTreeNode.size() > 0) {  
            for (Tags record : listParentTreeNode) {  
                // 添加所有子级  
                record.getChildren().addAll(getTreeChildTreeNode(listNotParentTreeNode, record.getId()));  
            }  
        }  
        return listParentTreeNode;  
    }  

    /** 
     *  递归查询子节点 
     */  
    private static List<Tags> getTreeChildTreeNode(List<Tags> childList, Long parentUuid) {  
        List<Tags> listParentTreeNode = new ArrayList<Tags>();  
        List<Tags> listNotParentTreeNode = new ArrayList<Tags>();  
        // 遍历tmpList，找出所有的根节点和非根节点  
        if (childList != null && childList.size() > 0) {  
            for (Tags record : childList) {  
                // 对比找出父节点  
                if (StringUtils.equals(String.valueOf(record.getParentId()),String.valueOf(parentUuid))) {  
                    listParentTreeNode.add(record);  
                } else {  
                    listNotParentTreeNode.add(record);  
                }  
            }  
        }  
        // 查询子节点  
        if (listParentTreeNode.size() > 0) {  
            for (Tags record : listParentTreeNode) {  
                // 递归查询子节点  
                record.getChildren().addAll(getTreeChildTreeNode(listNotParentTreeNode, record.getId()));  
            }  
        }  
        return listParentTreeNode;  
    }  
    
}  